package com.shuyuansystem.controller;

import com.shuyuansystem.dao.CheckRoleMapper;
import com.shuyuansystem.entity.Result;
import com.shuyuansystem.pojo.Product;
import com.shuyuansystem.pojo.User;
import com.shuyuansystem.service.MerchantProductService;
import com.shuyuansystem.service.ProductService;
import com.shuyuansystem.utils.JWTUtils;
import com.shuyuansystem.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/MerchantProduct")
public class MerchantProductController {

    @Autowired
    private CheckRoleMapper checkRoleMapper;
    @Autowired
    private MerchantProductService merchantProductService;
    @Autowired
    private ProductService productService;

    @GetMapping("/getRoleAndUserId")
    public User getRoleAndUserId(@RequestHeader("Authorization") String token) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 去除 Bearer 前缀
            token = token.replace("Bearer ", "");
            // 从 Token 中获取用户 ID
            String userId = JWTUtils.getUserIdFromToken(token);
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无法从 Token 中获取用户 ID");
                return null;
            }
            // 根据用户 ID 查询角色
            String role = checkRoleMapper.checkRoleById(userId);
            if (role == null) {
                response.put("success", false);
                response.put("message", "未找到该用户的角色信息");
                return null;
            }

            User user = new User();
            user.setId(Integer.parseInt(userId));
            user.setRole(role);
            return user;
        } catch (Exception e) {
            return null;
        }
    }

    @GetMapping("/setProduct")
    public Map<String, Object> setProduct(@RequestParam("userId") String userId,
                                          @RequestParam("currentPage") int currentPage,
                                          @RequestParam("pageSize") int pageSize) {
        System.out.println("接收到的用户 ID: " + userId);

        int userId2 = Integer.parseInt(userId);
        List<Integer> productIds = merchantProductService.getProductIdsByUserId(userId2);
        int offset = (currentPage - 1) * pageSize;
        List<Product> products = productService.getProductsByProductIdsWithPagination(productIds, offset, pageSize);
        int total = productService.getTotalCountByProductIds(productIds);

        Map<String, Object> result = new HashMap<>();
        result.put("rows", products);
        result.put("total", total);
        return result;
    }

    @PostMapping("/updateProduct")
    public Map<String, Object> updateProduct(@RequestParam("productId") Integer productId,
                                             @RequestParam("productName") String productName,
                                             @RequestParam("price") Double price,
                                             @RequestParam("description") String description,
                                             @RequestParam(value = "image", required = false) MultipartFile image) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 先查询旧商品信息，用于后续判断是否需要删除旧图片
            Product oldProduct = productService.getProductById(productId);
            if (oldProduct == null) {
                response.put("success", false);
                response.put("message", "未找到该商品信息");
                return response;
            }

            String imageUrl = oldProduct.getImage_url();
            // 如果有新图片上传
            if (image != null && !image.isEmpty()) {
                try {
                    // 上传图片到七牛云
                    String fileName = System.currentTimeMillis() + "_" + image.getOriginalFilename();
                    imageUrl = QiniuUtils.upload2Qiniu(image.getBytes(), fileName);
                    if (imageUrl == null) {
                        response.put("success", false);
                        response.put("message", "图片上传到七牛云失败");
                        return response;
                    }
                    // 如果旧图片存在，删除旧图片
                    if (oldProduct.getImage_url() != null) {
                        String oldFileName = oldProduct.getImage_url().substring(oldProduct.getImage_url().lastIndexOf("/") + 1);
                        QiniuUtils.deleteFileFromQiniu(oldFileName);
                    }
                } catch (IOException e) {
                    response.put("success", false);
                    response.put("message", "处理图片文件时出错: " + e.getMessage());
                    return response;
                }
            }

            // 更新商品信息
            Product product = new Product();
            product.setProduct_id(productId);
            product.setProduct_name(productName);
            product.setPrice(BigDecimal.valueOf(price));
            product.setDescription(description);
            product.setImage_url(imageUrl);

            boolean updateResult = productService.updateProduct(product);
            if (updateResult) {
                response.put("success", true);
                response.put("message", "商品信息更新成功");
            } else {
                response.put("success", false);
                response.put("message", "商品信息更新失败");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "更新商品信息时出错: " + e.getMessage());
        }
        return response;
    }
    @PostMapping("/deleteProduct")
    public Map<String, Object> deleteProduct(@RequestParam("productId") Integer productId) {
        Map<String, Object> response = new HashMap<>();
        try {
            boolean result = productService.deleteProduct(productId);
            if (result) {
                response.put("success", true);
                response.put("message", "商品删除成功");
            } else {
                response.put("success", false);
                response.put("message", "商品删除失败");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "删除商品时出错: " + e.getMessage());
        }
        return response;
    }
    @PostMapping("/addProduct")
    public Map<String, Object> addProduct(@RequestHeader("Authorization") String token,
                                          @RequestParam("productName") String productName,
                                          @RequestParam("price") Double price,
                                          @RequestParam("description") String description,
                                          @RequestParam(value = "image", required = false) MultipartFile image) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 去除 Bearer 前缀
            token = token.replace("Bearer ", "");
            // 从 Token 中获取用户 ID
            String userId = JWTUtils.getUserIdFromToken(token);
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无法从 Token 中获取用户 ID");
                return response;
            }

            String imageUrl = null;
            // 如果有图片上传
            if (image != null && !image.isEmpty()) {
                try {
                    // 上传图片到七牛云
                    String fileName = System.currentTimeMillis() + "_" + image.getOriginalFilename();
                    imageUrl = QiniuUtils.upload2Qiniu(image.getBytes(), fileName);
                    if (imageUrl == null) {
                        response.put("success", false);
                        response.put("message", "图片上传到七牛云失败");
                        return response;
                    }
                } catch (IOException e) {
                    response.put("success", false);
                    response.put("message", "处理图片文件时出错: " + e.getMessage());
                    return response;
                }
            }

            // 创建新的商品对象
            Product product = new Product();
            product.setProduct_name(productName);
            product.setPrice(BigDecimal.valueOf(price));
            product.setDescription(description);
            product.setImage_url(imageUrl);

            // 调用服务层方法添加商品
            boolean addResult = productService.addProduct(product);
            if (addResult) {
                // 获取新商品的 ID
                Integer productId = product.getProduct_id();
                // 在 merchant_products 表中创建关联记录
                boolean associationResult = merchantProductService.addMerchantProductAssociation(Integer.parseInt(userId), productId);
                if (associationResult) {
                    response.put("success", true);
                    response.put("message", "商品新增成功，关联记录创建成功");
                } else {
                    response.put("success", false);
                    response.put("message", "商品新增成功，但关联记录创建失败");
                }
            } else {
                response.put("success", false);
                response.put("message", "商品新增失败");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "新增商品时出错: " + e.getMessage());
        }
        return response;
    }
}